package com.qdlc.p2p.quartz;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.apache.log4j.Logger;

import java.io.File;

public class FileMonitor extends FileAlterationListenerAdaptor {
    private static final Logger LOG = Logger.getLogger("job");

    private static FileMonitor fileMonitor;

    private FileMonitor() {
    }

    // Get singleton object instance
    public static FileMonitor getFileMonitor() {
        if (fileMonitor == null) {
            synchronized (FileMonitor.class) {
                if (fileMonitor == null) {
                    fileMonitor = new FileMonitor();
                }
            }
        }
        return fileMonitor;
    }

    // Create file event
    @Override
    public void onFileCreate(File file) {
        LOG.info("[Create]: " + file.getAbsolutePath());
    }

    // Change file event
    @Override
    public void onFileChange(File file) {
        LOG.info("[Change]: " + file.getAbsolutePath());
        if("quartz".equals(FilenameUtils.getBaseName(file.getAbsolutePath()))){
            QuartzConfigManager.loadQuartzConfig();
        }
    }

    // Delete file event
    @Override
    public void onFileDelete(File file) {
        LOG.info("[Delete]: " + file.getAbsolutePath());
    }

    public void monitor(String directory, int interval) {
        LOG.debug(String.format("monitor directory[%s]",directory));
        // Observer file whose suffix is pm
        FileAlterationObserver fileAlterationObserver = new FileAlterationObserver(directory, FileFilterUtils.and(FileFilterUtils.fileFileFilter(),
                FileFilterUtils.suffixFileFilter(".properties")), null);

        // Add listener for event (file create & change & delete)
        fileAlterationObserver.addListener(this);

        // Monitor per interval
        FileAlterationMonitor fileAlterationMonitor = new FileAlterationMonitor(interval, fileAlterationObserver);

        try {
            // Start to monitor
            fileAlterationMonitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
